<template>
  <div>
    <Drawer
      ref="modal"
      :title="`${editType === 'create' ? $t('versionIndex.VersionEditAdd') : $t('versionIndex.VersionEditEdit')}`"
      :width="600"
      :value="show"
      :beforeClose="$_modal_decideIfClose"
    >
      <Form
        ref="form"
        :labelWidth="100"
        :model="formData"
        :rules="formRule"
      >
        <FormItem prop="deviceType" :label="$t('devicesIndex.upgradeType')">
          <Select
            style="width:200px"
            v-model="formData.deviceType"
            :placeholder="$t('devicesCreate.devCreateTypeHint')"
          >
            <Option
              v-for="(item, idx) in deviceType" :key="idx"
              :value="item.value"
              :label="item.name"
            >
            </Option>
          </Select>
        </FormItem>
        <FormItem prop="apkname" :label="$t('versionIndex.verListName')">
          <Input v-model="formData.apkname"  :placeholder="$t('versionIndex.verListInput')" />
        </FormItem>
        <FormItem prop="version" :label="$t('versionIndex.verListVersion')">
          <Input v-model="formData.version" :placeholder="$t('versionIndex.verListVersionInput')" />
        </FormItem>
        <FormItem prop="isForce" :label="$t('versionIndex.verListRestartIs')">
          <i-switch
            v-model="formData.isForce"
            :true-value="1"
            :false-value="0"
            size="large"
          >
            <span slot="open">{{ $t("versionIndex.verListRestartIsY") }}</span>
            <span slot="close">{{ $t("versionIndex.verListRestartIsN") }}</span>
          </i-switch>
        </FormItem>
        <FormItem prop="file" :label="$t('versionIndex.verListFile')">
          <Upload
            v-model="formData.file"
            action="/"
            :before-upload="handleUpload"
          >
            <Button icon="ios-cloud-upload-outline">{{ $t("versionIndex.verListFileSel") }}</Button>
          </Upload>
          <span v-if="ifSelFile">{{ formData.file.name }}</span>
        </FormItem>
        <FormItem prop="msg" :label="$t('versionIndex.verListRemark')">
          <Input
            v-model="formData.msg"
            :placeholder="$t('versionIndex.verListRemarkInput')"
            type="textarea"
            :rows="4"
          />
        </FormItem>
        <FormItem class="glo-btn-group">
          <Button
            type="primary"
            :loading="loading"
            @click="handleSubmit"
          >{{ $t("devicesCreate.devCreateSubmit") }}</Button>
          <Button
            @click="$_modal_close"
          >{{ $t("devicesCreate.devCreateCancel") }}</Button>
        </FormItem>
      </Form>
    </Drawer>
  </div>
</template>

<script>
import _ from 'lodash'
import {
  mapState,
} from 'vuex'

import modalMixin from '@/utils/mixins/modalMixin.js'
import {
  create,
  update,
  detail,
} from '@/api/version.js'

const DEFAULT_FORM = {
  deviceType: 'F800W',
  apkname: '',
  version: '',
  isForce: 1,
  file: '',
  msg: '',
}

export default {
  mixins: [
    modalMixin,
  ],

  props: {
    editType: {
      type: String,
      default: 'create',
    },
    editItem: Object,
  },
  data () {
    return {
      deviceType: [
        { name: 'F800W', value: 'F800W' },
        { name: 'F800A', value: 'F800A' },
        { name: 'D2', value: 'D2' },
        { name: 'D2W', value: 'D2W' },
        { name: 'D2-F700A', value: 'D2-F700A' },
        { name: 'D2-F700AW', value: 'D2-F700AW' },
        { name: 'D2-B', value: 'D2-B' },
        { name: 'D2-3', value: 'D2-3' },
        { name: 'D2-4', value: 'D2-4' },
      ],
      formData: _.cloneDeep(DEFAULT_FORM),
      formRule: {
        deviceType: { required: true, message: this.$t('versionIndex.verListIfType') },
        apkname: { required: true, message: this.$t('versionIndex.verListIfName') },
        version:  {required: true,validator: (rule, value, callback) => {
          // var reg = /^[1-9]\d*\,\d*|[0-9]\d*$/g;  //必须为数字，但是允许小数点
          // var reg = /[^\d^\.]+/;  //必须为数字，但是允许小数点
          // var reg = /\d+(.\d+)*/g;  //必须为数字，但是允许小数点
          var reg = /^[1-9]\d*\.\d+$|^[1-9]\d*\.\d+\.\d+$|^[1-9]\d*\.\d+\.\d+\.\d+$/g;  //必须为数字，但是允许小数点
          if (!reg.test(value)) {
            return callback(new Error(this.$t('versionIndex.verListIfVersionTip')))
          } else {
            return callback()
          }
        }, trigger: 'blur' },
        file: { required: true, message: this.$t('versionIndex.verListIfFile') },
        msg: { required: true, message: this.$t('versionIndex.verListIfRemark') },
      },
    }
  },
  computed: {
    ...mapState([
      'departId',
    ]),
    ifSelFile () {
      return typeof this.formData.file === 'object'
    },
  },

  mounted () {
    this.show = true
    if (this.editType === 'update') {
      this.getDetail(this.editItem.id)
    }
  },

  methods: {
    handleUpload (file) {
      this.formData.file = file
      return false
    },
    generateFormData () {
      const data = _.cloneDeep(this.formData)
      const formData = new FormData()
      const keys = Object.keys(data)
      for (let i = 0; i < keys.length; i += 1) {
        const key = keys[i]
        formData.append(key, data[key])
      }
      return formData
    },

    async handleSubmit () {
      const ifVlid = await this.$refs.form.validate()
      if (ifVlid && this.editType === 'create') {
        this.handleCreate()
      }
      if (ifVlid && this.editType === 'update') {
        this.handleUpdate()
      }
    },

    async getDetail (areaId) {
      const { success, data } = await detail({ areaId })
      if (success) {
        const netForm = data.data
        const formData = {}
        const keys = Object.keys(DEFAULT_FORM)
        keys.forEach(key => {
          formData[key] = _.isUndefined(netForm[key])
            ? DEFAULT_FORM[key]
            : netForm[key]
        })
        formData.id = netForm.id
        this.formData = _.cloneDeep(formData)
      }
    },
    async handleCreate () {
      const formData = this.generateFormData()
      const { success, data } = await create(formData)
      if (success) {
        this.$Message.success(this.$t('devicesCreate.devCreateS'))
        this.ifUpdateUpper = true
        this.$_modal_close()
      } else {
        this.$Message.error(data)
      }
    },
    async handleUpdate () {
      const formData = this.generateFormData()
      const { success, data } = await update(formData)
      if (success) {
        this.$Message.success(this.$t('devicesCreate.devCreateUpdateS'))
        this.ifUpdateUpper = true
        this.$_modal_close()
      } else {
        this.$Message.error(data)
      }
    },
  },
}
</script>
